package com.eastfair.weixin.controller;


import com.eastfair.core.base.R;
import com.eastfair.core.utils.XmlUtil;
import com.eastfair.weixin.service.OfficialEventService;
import com.eastfair.wx.service.QuickMarkService;
import com.eastfair.wx.util.SignUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;

@Controller
@RequestMapping("/api")
@Slf4j
public class WxApiController {

    private static final Logger logger = LoggerFactory.getLogger(WxApiController.class);

    @Autowired
    QuickMarkService quickMarkService;
    @Autowired
    OfficialEventService officialEventService;
    @Autowired
    SignUtil signUtil;
    /**
     * 查询服务号二维码
     */
    @RequestMapping(value = "/getCode", method = RequestMethod.GET)
    @ResponseBody
    public R<String> getCode(String userId) {
       return R.success(quickMarkService.findCode());
    }

    @ApiOperation(value = "微信回调方法", notes = "微信回调方法")
    @RequestMapping(value = {"/event"}, method = {RequestMethod.GET, RequestMethod.POST})
    public void event(HttpServletRequest request, HttpServletResponse response) {
        log.info("-------------------------微信回调event");
        try {
            String msg = parse(request);
            Map<String, String> xmlMap = XmlUtil.xmlToMap(msg);
            logger.info("收到微信回调:{}", xmlMap);
            String event = xmlMap.get("event");
            if("subscribe".equals(event)){
                //关注
                officialEventService.subscribe(xmlMap);
            }else if("unsubscribe".equals(event)){
                //取消关注
                officialEventService.unsubscribe(xmlMap);
            }
            //校验接口信息，校验通过则不需要了
//            logger.info("signature is :{}", request.getParameter("signature"));
//            logger.info("timestamp is :{}", request.getParameter("timestamp"));
//            logger.info("nonce is :{}", request.getParameter("nonce"));
//            logger.info("eventkey is :{}", request.getParameter("eventkey"));
//            if (StringUtils.isNotBlank(request.getParameter("signature"))) {
//                String signature = request.getParameter("signature");
//                String timestamp = request.getParameter("timestamp");
//                String nonce = request.getParameter("nonce");
//                String echostr = request.getParameter("echostr");
//                log.info("signature[{}], timestamp[{}], nonce[{}], echostr[{}]", signature, timestamp, nonce, echostr);
//                if (signUtil.checkSignature(signature, timestamp, nonce)) {
//                    log.info("数据源为微信后台，将echostr[{}]返回！", echostr);
//                    response.getOutputStream().println(echostr);
//                }
//            }
//                Map<String, String> xmlMap = XmlUtils.xmlToMap(notifyXml);
            // 发布事件
//                NormalMsgEvent normalMsgEvent = new NormalMsgEvent(applicationContext, xmlMap, appId);
//                applicationContext.publishEvent(normalMsgEvent);
        } catch (Exception e) {
            logger.error("微信消息回调异常", e);
        }
//        return null;
    }

    private String parse(HttpServletRequest request) {
        BufferedReader buf = null;
        try {
            buf = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while (null != (line = buf.readLine())) {
                sb.append(line);
            }
            if (sb.length() > 0) {
                return sb.toString();
            }
        } catch (Exception e) {
            log.error("微信回调解析异常");
            return null;
        } finally {
            try {
                buf.close();
            } catch (Exception e) {
                log.error("weimob parse request error!", e);
            }
        }
        return null;
    }
}
